package com.pactera.madp.cp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.cp.api.dto.marketing.*;
import com.pactera.madp.cp.api.entity.marketing.MarketingArticleEntity;
import com.pactera.madp.cp.api.vo.marketing.MarketingArticleVO;
import com.pactera.madp.cp.common.config.FileUploadConfig;
import com.pactera.madp.cp.common.constant.TemplateCss;
import com.pactera.madp.cp.common.util.QRCodeUtil;
import com.pactera.madp.cp.handler.CorpContextHolder;
import com.pactera.madp.cp.mapper.marketing.MarketingArticleMapper;
import com.pactera.madp.cp.service.MarketingArticleService;
import com.pactera.madp.cp.service.MarketingHotService;
import com.pactera.madp.cp.service.WechatComponentService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.*;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (McMarketingArticle)表服务实现类
 *
 * @author yushen.qi
 * @since 2021-05-24 15:30:54
 */
@Service
@Data
@Slf4j
public class MarketingArticleServiceImpl extends ServiceImpl<MarketingArticleMapper, MarketingArticleEntity> implements MarketingArticleService {

    private final FileUploadConfig fileUploadConfig;
    @Resource
    private MarketingHotService marketingHotService;
    @Resource
    private WechatComponentService wechatComponentService;

    @Override
    public List<MarketingArticleVO> selectAllOrName(String title, Integer classification) {
        int corpId = CorpContextHolder.getCorpId();
        List<MarketingArticleVO> collect;
        //判断title是否为空，不是则为模糊查询。
        if(null==title){
            collect = list(Wrappers.<MarketingArticleEntity>lambdaQuery().eq(MarketingArticleEntity::getCorpId, corpId).eq(MarketingArticleEntity::getClassification,classification).eq(MarketingArticleEntity::getArAttribute,0)).stream().map(entity ->
            {
                MarketingArticleVO articleVO = new MarketingArticleVO();
                BeanUtil.copyProperties(entity, articleVO);
                return articleVO;
            }).collect(Collectors.toList());
        }else {
            collect = list(Wrappers.<MarketingArticleEntity>lambdaQuery().eq(MarketingArticleEntity::getCorpId, corpId).like(MarketingArticleEntity::getTitle, title).eq(MarketingArticleEntity::getArAttribute,0).eq(MarketingArticleEntity::getClassification,classification)).stream().map(entity ->
            {
                MarketingArticleVO articleVO = new MarketingArticleVO();
                BeanUtil.copyProperties(entity, articleVO);
                return articleVO;
            }).collect(Collectors.toList());
        }
        return collect;
    }

    @Override
    public IPage selectAllByPageOrName(Page page,String title, Integer classification) {
        Integer corpId = CorpContextHolder.getCorpId();
        QueryWrapper<MarketingArticleEntity> wrapper = new QueryWrapper<>();
        if(null==title){
            wrapper.eq("corp_id",corpId).eq("marketing_state",2).eq("classification",classification);
        }else {
            wrapper.like("title",title).eq("marketing_state",2).eq("corp_id",corpId).eq("classification",classification);
        }
        IPage iPage = baseMapper.selectPage(page, wrapper);
        Object collect = iPage.getRecords().stream().map(entity -> {
            MarketingArticleVO articleVO = new MarketingArticleVO();
            BeanUtil.copyProperties(entity, articleVO);
            return articleVO;
        }).collect(Collectors.toList());
        iPage.setRecords((List) collect);
        return iPage;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Integer> insert(MarketingArticleCreateDTO dto) {
        MarketingArticleEntity articleEntity = new MarketingArticleEntity();
        BeanUtil.copyProperties(dto,articleEntity);
        int corpId = CorpContextHolder.getCorpId();
        int tenantId = AccountService.getTenantId();
        //设置新增文章的参数。
        articleEntity.setCreateTime(LocalDateTime.now());
        articleEntity.setUpdateTime(LocalDateTime.now());
        articleEntity.setCorpId(corpId);
        articleEntity.setTenantId(tenantId);
        articleEntity.setMarketingState(1);
        articleEntity.setRecState(2);
        articleEntity.setHotUuid("a");
        //新建文件夹
        File file=new File(fileUploadConfig.getRealPath()+File.separator+"articleHtml");
        //如果文件夹不存在
        if(!file.exists()){
            //创建文件夹
            file.mkdir();
        }
        //判断是否有模板文件，没有则创建。
        File fileName=new File(file+File.separator+"template.html");
        if(!fileName.exists())
        {
            try {
                file.createNewFile();
                log.info("文件创建成功");
                //用于存储html字符串
                PrintStream printStream = new PrintStream(new FileOutputStream(fileName));
                StringBuilder stringHtml = new StringBuilder();
                stringHtml.append(TemplateCss.templateTxt);
                //输入HTML文件内容
                printStream.println(stringHtml.toString());
                printStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            log.info("文件已存在！");
        }
        //新建文章html文件.
        try {
            //建立文件
            String title=dto.getTitle()+dto.getArAuthor()+dto.getArBody();
            String templateContent="";
            //根据nacos配置的文件存储路径建立文件。
            FileInputStream fileinputstream = new FileInputStream(fileUploadConfig.getRealPath()+File.separator+"articleHtml"+File.separator+"template.html");// 读取模板文件
             //   得到文件大小
            int lenght = fileinputstream.available();
            byte bytes[] = new byte[lenght];
            fileinputstream.read(bytes);
            fileinputstream.close();
            templateContent = new String(bytes);
            templateContent = templateContent.replaceAll("###title###", title);
            String fileame = IdUtil.objectId();
          //  String url = QRCodeUtil.main(fileame,fileUploadConfig);
            //文件名称
            fileame = fileame+ ".html";
            //虚拟地址
           String newFileName= fileUploadConfig.getAccessPath()+File.separator+"articleHtml"+File.separator+ fileame;
            // 生成的html文件保存路径。
            fileame = fileUploadConfig.getRealPath()+File.separator+"articleHtml"+File.separator+ fileame;
            // 建立文件输出流
            FileOutputStream fileoutputstream = new FileOutputStream(fileame);
            byte tag_bytes[] = templateContent.getBytes();
            fileoutputstream.write(tag_bytes);
            //释放资源
            fileoutputstream.close();
            //设置文件的访问地址，存储地址
          articleEntity.setMarketingUrl(newFileName);
          articleEntity.setMarketingHtmlUrl(fileame);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //保存新增的文章
        save(articleEntity);
        //获取刚刚新增的文章
        MarketingArticleEntity one = getOne(Wrappers.<MarketingArticleEntity>lambdaQuery().eq(MarketingArticleEntity::getCorpId,corpId).orderByDesc(MarketingArticleEntity::getId).last("limit 1"));
        HashMap<String, Integer> hashMap = new HashMap<>(1);
        hashMap.put("id",one.getId());
        //返回id给前端。
        return hashMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(MarketingArticleUpdateDTO marketingArticleUpdateDto) {
        MarketingArticleEntity one = getOne(Wrappers.<MarketingArticleEntity>lambdaQuery().eq(MarketingArticleEntity::getId, marketingArticleUpdateDto.getId()));
        String substring = one.getMarketingUrl().substring(one.getMarketingUrl().lastIndexOf(File.separator) + 1);
        try {
                //建立文件
                String body =marketingArticleUpdateDto.getArBody();
                String templateContentOne = "";
                // 读取旧版本文件
                FileInputStream fileinputstream = new FileInputStream(fileUploadConfig.getRealPath() + File.separator + "articleHtml" + File.separator + substring);
                int length = fileinputstream.available();
                byte[] bytes = new byte[length];
                fileinputstream.read(bytes);
                fileinputstream.close();
                templateContentOne = new String(bytes);
                templateContentOne = templateContentOne.replace(one.getArBody(), body);
                byte[] tagBytes = templateContentOne.getBytes();
                // 输出新版本文件
                FileOutputStream fileOutputStream = new FileOutputStream(fileUploadConfig.getRealPath() + File.separator + "articleHtml" + File.separator + substring);
                fileOutputStream.write(tagBytes);
                //释放流
                fileOutputStream.close();
                String fileName = fileUploadConfig.getRealPath() + File.separator + "articleHtml" + File.separator + substring;
                MarketingArticleEntity marketingArticleEntity = new MarketingArticleEntity();
                BeanUtil.copyProperties(marketingArticleUpdateDto,marketingArticleEntity);
                marketingArticleEntity.setUpdateTime(LocalDateTime.now());
               marketingArticleEntity.setMarketingState(3);
               marketingArticleEntity.setHotUuid(null);
               marketingArticleEntity.setRecState(2);
                marketingArticleEntity.setMarketingHtmlUrl(fileName);
                return   update(marketingArticleEntity,Wrappers.<MarketingArticleEntity>lambdaQuery().
                    eq(MarketingArticleEntity::getId,marketingArticleEntity.getId()));
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        return false;
    }

    @Override
    public R remove(Integer id) {
        MarketingArticleEntity one = getOne(Wrappers.<MarketingArticleEntity>lambdaQuery().eq(MarketingArticleEntity::getId, id));
        if (one.getMarketingState()==2){
            return R.failed("该素材已被发布，无法删除！");
        }
        if(one.getRecState()==1){
            return R.failed("该素材已被推荐，无法删除！");
        }
//        MarketingHotEntity hotEntity = marketingHotService.getOne(Wrappers.<MarketingHotEntity>lambdaQuery().eq(MarketingHotEntity::getCorpId,CorpContextHolder.getCorpId()).orderByDesc(MarketingHotEntity::getId).last("limit 1"));
//       if(null!=hotEntity){
//           if(one.getHotUuid().equals(hotEntity.getHotUuid())){
//               return R.failed("该素材已在热榜发布，无法删除！");
//           }
//       }
        return remove(Wrappers.<MarketingArticleEntity>lambdaQuery().eq(MarketingArticleEntity::getId,id))?R.ok():R.failed("删除失败！");
    }

    @Override

    public R previewArticle(MarketingArticlePreviewDTO dto) {
        //新建文件夹
        File file=new File(fileUploadConfig.getRealPath()+File.separator+"temp");
        //如果文件夹不存在
        if(!file.exists()){
            //创建文件夹
            file.mkdir();
        }
        //建立模板文件
        File fileName=new File(file+File.separator+"template.html");
        if(!fileName.exists())
        {
            try {
                file.createNewFile();
                log.info("文件创建成功");
                //用于存储html字符串
                PrintStream printStream = new PrintStream(new FileOutputStream(fileName));
                StringBuilder stringHtml = new StringBuilder();
                stringHtml.append(TemplateCss.templateTxt);
                //输入HTML文件内容
                printStream.println(stringHtml.toString());
                printStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            log.info("文件已存在！");
        }
        //新建文章html文件.
        try {
            //建立文件
            String title=dto.getTitle()+dto.getArAuthor()+dto.getArBody();
            String templateContent="";
            FileInputStream fileinputstream = new FileInputStream(fileUploadConfig.getRealPath()+File.separator+"articleHtml"+File.separator+"template.html");// 读取模板文件
            int lenght = fileinputstream.available();
            byte bytes[] = new byte[lenght];
            fileinputstream.read(bytes);
            fileinputstream.close();
            templateContent = new String(bytes);
            templateContent = templateContent.replaceAll("###title###", title);
            String fileame = IdUtil.objectId();
            String url = QRCodeUtil.main(fileame,fileUploadConfig);
            fileame = fileame+ ".html";
            // 生成的html文件保存路径。
            fileame = fileUploadConfig.getRealPath()+File.separator+"temp"+File.separator+ fileame;
            // 建立文件输出流
            FileOutputStream fileoutputstream = new FileOutputStream(fileame);
            byte tag_bytes[] = templateContent.getBytes();
            fileoutputstream.write(tag_bytes);
            fileoutputstream.close();
            return R.ok(url);
        } catch (Exception e) {
            log.info(e.getMessage());
            return R.failed("生成失败"+e.getMessage());
        }
    }

    @Override
    public R saveMaterial(MarketingMaterialUpdateDTO dto) {
        UpdateWrapper<MarketingArticleEntity> wrapper = new UpdateWrapper<>();
        wrapper.set("track_behavior",dto.getTrackBehavior())
                .set("track_dynamic",dto.getTrackDynamic())
                .set("update_time",LocalDateTime.now())
                .eq("id",dto.getId());
        return update(null,wrapper)?R.ok():R.failed("发布失败！");
    }

    @Override
    public R updateMaterial(MarketingMaterialUpdateDTO dto) {
        UpdateWrapper<MarketingArticleEntity> wrapper = new UpdateWrapper<>();
        wrapper.set("marketing_state",2)
                .set("track_behavior",dto.getTrackBehavior())
                .set("track_dynamic",dto.getTrackDynamic())
                .set("update_time",LocalDateTime.now())
                .eq("id",dto.getId());
        return update(null,wrapper)?R.ok():R.failed("发布失败！");
    }

    @Override
    public List<MarketingArticleVO> selectMaterial(String appId,String title,Integer classification) {
        Integer corpId = CorpContextHolder.getCorpId();
        List<MarketingArticleVO> collect;
       if(StringUtils.isNotEmpty(title)){
           collect = list(Wrappers
                   .<MarketingArticleEntity>lambdaQuery()
                   .eq(MarketingArticleEntity::getAuthorizerAppId, appId)
                   .eq(MarketingArticleEntity::getClassification, classification)
                   .eq(MarketingArticleEntity::getCorpId, corpId)
                   .like(MarketingArticleEntity::getTitle,title))
                   .stream().map(entity -> {
                       MarketingArticleVO marketingArticleVO = new MarketingArticleVO();
                       BeanUtil.copyProperties(entity, marketingArticleVO);
                       return marketingArticleVO;
                   }).collect(Collectors.toList());
       }else {
        collect = list(Wrappers
                .<MarketingArticleEntity>lambdaQuery()
                .eq(MarketingArticleEntity::getAuthorizerAppId, appId)
                .eq(MarketingArticleEntity::getClassification, classification)
                .eq(MarketingArticleEntity::getCorpId, corpId))
                .stream().map(entity -> {
                    MarketingArticleVO marketingArticleVO = new MarketingArticleVO();
                    BeanUtil.copyProperties(entity, marketingArticleVO);
                    return marketingArticleVO;
                }).collect(Collectors.toList());
       }
        return collect;
    }
}
